<template>
  <el-form class="BaseForm" ref="form" :model="prompt" label-width="88px" label-position="top">
    <el-scrollbar class="formContent">
      <div class="formTitle">基础图片</div>
      <el-form-item class="formItem">
        <ImagePicker TipsTxt="请上传需要二创的图片" ToPlatform="No-ComfyUI" @change="ChangeModelImg" :DefaultImageUrl="imageUrl"></ImagePicker>
      </el-form-item>
      <div class="formTitle">高级模式</div>
      <el-form-item class="formItem">
        <el-switch v-model="advance" active-text="开" inactive-text="关" />
      </el-form-item>
      <div class="advanceMode" v-if="advance">
        <el-form-item class="formItem" label="还原度" style="padding:0 40px 0 0;">
          <el-slider style="margin: 0 0 36px 18px;" v-model="reduction" :step="1.5" :max="3" show-stops :format-tooltip="showReductionTxt" :marks="reductionMarks"/>
        </el-form-item>
        <el-form-item class="formItem" label="智能描述">
          <el-switch v-model="autoPrompt" active-text="开" inactive-text="关" />
        </el-form-item>
        <el-form-item class="formItem" label="基础描述">
          <el-input v-model="prompt.txt" type="textarea" :placeholder="promptTips()" rows="6"></el-input>
        </el-form-item>
        <el-form-item class="formItem nowMargin">
        <el-tabs class="formTab" v-if="promptSetting!=null" v-model="nowTab" @tab-click="changePromptTab" lazy="true" v-loading="isLoadingPrompt">
          <el-tab-pane v-for="(tab, index) in promptSetting.tabList" :label="tab.title" :name="tab.tabId">
            <PromptSession v-if="tab.tabId == nowTab" v-for="( session, index ) in tab.sessionGroup" 
            :key="index" 
            :Session="promptSetting.groupList.filter(ses=>ses.groupId == session)[0]" 
            :SelecterList="promptSetting.sessionList"
            @change="sessionDataChange"></PromptSession>
          </el-tab-pane>
        </el-tabs>
        </el-form-item>
      </div>
    </el-scrollbar>
    <div class="formBottomBar">
      <div class="content">
        <div class="tips">描述建议<br />图片主体 + 环境背景 + 图片风格</div>
      </div>
      <el-button round class="FormBtn" @click="onSubmit" v-loading="nowLoading"><el-icon class="icon"><Brush /></el-icon><span class="txt">生成图片</span></el-button>
    </div>
  </el-form>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .advanceMode{border-radius: 18px; background: #f9f9f9; padding: 12px; margin-bottom: 24px;}
  .BaseForm .formItem.nowMargin{margin-bottom: 0;}
</style>
<style>
</style>
<script>
import WebRequest from '../../unit/request.js'
import PromptSession from '../element/PromptSession.vue'
import ImagePicker from '../element/ImagePicker.vue'
import OS from '../../unit/OS.js'
export default {
  name: 'Reimagine',
  components: { PromptSession,ImagePicker },
  props: {
    src: '',
    title: '',
    date: '',
    imageUrl: '',
    sourceImageDepotId:''
  },
  data () {
    return {
      prompt: {
        txt: '',
        sessionData: []
      },
      promptSetting: null,
      isLoadingPrompt: false,
      nowTab: '',
      nowLoading:false,
      advance: false,
      autoPrompt: true,
      reduction:3,
      reductionMarks:{
        0:'低',
        1.5:'中',
        3:'高'
      },
      sourceImageDepotIdVal:'',
      baseImage:''
    }
  },
  mounted(){
    if(this.promptSetting == null && !this.isLoadingPrompt)
    this.isLoadingPrompt = true
    WebRequest.GetSelecterSetting({
      callback: (res) => {
        if(res.status == 200 && res.data.errCode == 10000){
          this.promptSetting = JSON.parse(res.data.data)
          this.nowTab = this.promptSetting.tabList[0].tabId
          console.log(this.promptSetting)
          this.isLoadingPrompt = false
        }else{
          this.promptSetting = null
          this.isLoadingPrompt = false
        }
      }
    })
  },
  methods: {  
    getPromptData(){
      var tabData = this.promptSetting.tabList.filter(tab => tab.tabId == this.nowTab);
      var ApiData = {
        basePrompt: this.prompt.txt,
        optionPrompt: '',
        tabId:this.nowTab,
        tabName:tabData[0].title,
        promptList:'',
        promptValue:'',
        advanceMode:this.advance,
        reduciNum:this.reduction==1.5?1:this.reduction==3?2:this.reduction,
        useAi:this.autoPrompt,
        originalImage:this.baseImage
      }
      if(this.advance){
        var promptTxt = ''
        var parmTxt = ''
        var promptListObj = [];
        var promptValueObj = [];
        if(tabData.length > 0){
          promptTxt = tabData[0].basePrompt
          parmTxt = tabData[0].baseParm
        }
        this.prompt.sessionData.forEach(ses=>{
          if(ses.data.length > 0){
            var groupObj = {
              groupId: ses.groupId,
              title: ses.title,
              desc: ses.desc,
              includeSelecter:[]
            }
            ses.data.forEach(sel=>{
              var selecterObj = {
                selecterId: sel.selecterId,
                selOptionVal: sel.promptTxt,
                selOptionName: sel.optionName,
                selOptionId: sel.optionId
              }
              groupObj.includeSelecter.push(selecterObj);
              promptValueObj.push(sel.optionName)
              if(sel.promptType == 'prompt'){
                promptTxt = promptTxt == ''?sel.promptTxt:promptTxt+', '+ sel.promptTxt
              }else{
                parmTxt = parmTxt == ''?sel.promptTxt:parmTxt+' '+ sel.promptTxt
              }
            })      
            promptListObj.push(groupObj);
          }
        })
        ApiData.optionPrompt = promptTxt == ''?(parmTxt==''?'':parmTxt):(parmTxt==''?promptTxt:promptTxt + " " + parmTxt)
        if(ApiData.optionPrompt == ''){
          ApiData.optionPrompt = '--iw ' + ApiData.reduciNum
        }else{
          ApiData.optionPrompt += ' --iw ' + ApiData.reduciNum
        }
        ApiData.promptList = promptListObj
        ApiData.promptValue = promptValueObj
        console.log(ApiData);
        return ApiData;
      }else{
        ApiData.optionPrompt = '--iw 3' 
        ApiData.promptList = promptListObj
        ApiData.promptValue = promptValueObj
        console.log(ApiData);
        return ApiData;
      }
    },
    onSubmit(e){
      this.nowLoading = true;
      WebRequest.PreConsumerPoint({
        serviceType:6,
        callback: (res) => {
          console.log(res);
          if(res.data.errCode == 10000){
            var coseId = res.data.data.id;
            var prompt = this.getPromptData();
            var extend = OS.GetFormSetting({
              operationId: "6",
              operationName: '智能二创',
              describe: prompt.basePrompt,
              tabId:prompt.tabId,
              tabName:prompt.tabName,
              promptList:prompt.promptList,
              promptValue:prompt.promptValue,
              advanceMode:prompt.advanceMode,
              useAi:prompt.useAi,
              originalImage:prompt.originalImage,
              reduciNum:prompt.reduciNum
            })
            console.log(extend);
            var sourceImageDepotId = this.sourceImageDepotId//this.sourceImageDepotIdVal
            if(this.sourceImageDepotIdVal != ''){
              sourceImageDepotId = this.sourceImageDepotIdVal
            }
            WebRequest.ImgToImg({
              costId:coseId,
              promptFlag:this.advance?this.autoPrompt:true,//是否需要图转prompt,示例值(true)	
              imgUrls:[this.baseImage],//oss图片列表,需要数组格式
              basePrompt:prompt.basePrompt,
              optionPrompt:prompt.optionPrompt,
              extendValue: extend,
              sourceImageDepotId:sourceImageDepotId,
              callback:(e) => {
                if(e.data.errCode == 10000){
                  var taskId = e.data.data.taskId
                  WebRequest.SaveToLibrary({
                    tool: 12,
                    taskId: taskId,
                    indexList:[1,2,3,4],
                    callback: (_e) => {
                      this.nowLoading = false
                      if(e.data.errCode == 10000){
                        this.$emit('startGenerate',taskId);
                      }else{
                        console.log('保存图库失败',e)
                      }
                    },
                    error:(_e) => {
                      this.nowLoading = false
                      console.log('保存图库接口请求异常',e)
                    }
                  })
                }else{
                      this.nowLoading = false
                  console.log('请求生图失败',e)
                }
              },
              error: (e) => {
                this.nowLoading = false
                console.log('请求生图接口请求异常',e)
              }
            })
          }else{
            this.nowLoading = false
            console.log('扣费失败',res)
          }
        },
        error: (e) => {
            this.nowLoading = false
            console.log('扣费接口请求异常',res)
        }
      })
    },
    promptTips () {
      var tips = [
        '例：一个穿着白色长裙的漂亮女孩，站在咖啡店门口，枫叶在飘落，日落，电影风格',
        '例：一个美丽的上海女人，特写，王家卫电影风格',
        '例：一个可爱的小女孩在吃着雪糕，背景是儿童乐园，由彩色的气球，皮克斯动画风格',
        '例：夜晚的酒吧街，两边是冷光的霓虹灯，一对情侣牵手走在路上。'
      ]
      var random = Math.floor(Math.random() * tips.length)
      if (random >= tips.length) {
        random = 0
      }
      return tips[random]
    },
    changePromptTab(e){
      console.log(e)
    },
    sessionDataChange(e){
      var newSession = true;
      for(var i = 0; i< this.prompt.sessionData.length; i++){
        if(this.prompt.sessionData[i].groupId == e.groupId){
          this.prompt.sessionData[i] = JSON.parse(JSON.stringify(e));
          newSession = false;
        }
      }
      if(newSession){
        this.prompt.sessionData.push(e);
      }
    },
    showReductionTxt(num){
      switch(num){
        case 0:
          return '低';
          break;
        case 1.5:
          return '中';
          break;
        case 3:
          return '高';
          break;
        default:
          return ''
      }
    },
    ChangeModelImg (e) {
      console.log(e);
      if(e.fileName && e.fileName != null && e.fileName != ''){
        this.baseImage = e.fileName
      }else{
        this.baseImage = e.imageUrl
      }
      this.sourceImageDepotIdVal = e.sourceImageDepotId
    },
  }
}
</script>
